package com.xul.crowd.config;


import com.xul.crowd.constant.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xul
 * @create 2021-07-27 10:21
 */
@Configuration
// 启用web环境下的权限控制
@EnableWebSecurity
// 启用全局方法权限控制 并设置prePostEnabled = true 保证@PreAuthority @PostAuthority @PreFilter @PostFilter 生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    /**
     * 与SpringSecurity环境下请求授权相关
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 对请求进行授权
                .authorizeRequests()
                // 放行相关资源
                .antMatchers("/admin/to/login/page.html", "/bootstrap/**", "/css/**", "/fonts/**", "/img/**", "/jquery/**", " /layer/**", "/script/**", "/ztree/**")
                .permitAll()
                // 针对分页显示Admin数据设定访问控制
                //.antMatchers("/admin/get/page.html")
                // 具备经理的角色
                // .hasRole("经理")
                //.access("hasRole('经理') or hasAuthority('user:get')")
                // 其他任意请求
                .anyRequest()
                // 认证后访问
                .authenticated()
                .and()
                .exceptionHandling()
                // 403定制去的页面
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        httpServletRequest.setAttribute("exception", new Exception(CrowdConstant.MESSAGE_LOGIN_DENIED));
                        httpServletRequest.getRequestDispatcher("/WEB-INF/page/system-error.jsp").forward(httpServletRequest, httpServletResponse);
                    }
                })
                .and()
                // 房跨站请求伪造功能
                .csrf()
                // 禁用
                .disable()
                // 开启表单登录功能
                .formLogin()
                // 指定登录页面
                .loginPage("/admin/to/login/page.html")
                // 指定处理登录请求的地址
                .loginProcessingUrl("/security/do/login.html")
                // 指定登录成功后前往的地址
                .defaultSuccessUrl("/admin/to/main/page.html",true)
                // 账号的请求参数名称
                .usernameParameter("loginAcct")
                // 密码的请求参数名称
                .passwordParameter("userPswd")
                .and()
                // 开启退出功能
                .logout()
                // 指定退出登出地址
                .logoutUrl("/security/do/logout.html")
                // 指定退出成功后前往的地址
                .logoutSuccessUrl("/admin/to/login/page.html");
    }

    /**
     * 与SpringSecurity环境下用户登录相关
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 临时使用内存登录模式经行测试
        // auth.inMemoryAuthentication().withUser("xul").password("123456").roles("ADMIN");

        // 数据库登录模式
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }
}
